package com.ruoyi.common.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.google.common.collect.Maps;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.SneakyThrows;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

public class PDFUtils {

    private static Configuration configuration = null;
    private static final String FONT = "simhei.ttf";
    // 图片路径
    private static final String imagePath = "G:\\git\\crane\\ruoyi-biz\\src\\main\\resources\\template\\ljwx.png";

    public static void main(String[] args) {
        System.out.println(ServletUtils.getHostIp());
    }

    static {
        configuration = new Configuration();
        //freemarker的模板目录

        try {
            configuration.setClassLoaderForTemplateLoading(PDFUtils.class.getClassLoader(), "/template/");
            configuration.setDefaultEncoding("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SneakyThrows
    public static void createPdf(String content, String dest) {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));

//        // 定义页眉和页脚页码事件，PDFBuilder代码在后面
//        PDFBuilder2 builder = new PDFBuilder2();
//        //设置页面监听事件
//        writer.setPageEvent(builder);

        // step 3
        document.open();
        // step 4
        XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                new ByteArrayInputStream(content.getBytes()), Charset.defaultCharset(), new ChinaFontProvide());
        // step 5
        document.close();
    }

    @SneakyThrows
    public static void addWaterMark(String srcFile, String destFile, String qrURL, String text) {
        // 待加水印的文件
        PdfReader reader = new PdfReader(srcFile);
        // 加完水印的文件
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));

        int total = reader.getNumberOfPages() + 1;
        PdfContentByte content;

        // 设置透明度
        PdfGState gs = new PdfGState();
        gs.setFillOpacity(0.2f);
        // 设置字体
        BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

        File tempFile = FileUtil.createTempFile(new File("/temp"));
        File renameFile = FileUtil.rename(tempFile, "qrCode.png", true);

//        String encodeURL = URLEncoder.encode(QRURL + qrURL, "UTF-8");
        Image imghead = null;
        if (StrUtil.isNotBlank(qrURL)) {
            File qrFile = QrCodeUtil.generate(qrURL, 300, 300, renameFile);

            imghead = Image.getInstance(qrFile.getPath());

            imghead.setAlignment(Image.ALIGN_CENTER);
            //依照比例缩放
            imghead.scalePercent(12);
            // 设置图片的位置
            imghead.setAbsolutePosition(32f, 805f);
        }

        // 循环对每页插入水印
        for (int i = 1; i < total; i++) {
            // 水印的起始
            content = stamper.getOverContent(i);
            if (StrUtil.isNotBlank(qrURL)) {
                content.addImage(imghead);
            }
            content.setGState(gs);
            content.setFontAndSize(base, 30);
            // 开始
            content.beginText();
            // 设置颜色 默认为黑色
            content.setColorFill(BaseColor.BLACK);
            // 开始写入水印
            content.showTextAligned(Element.ALIGN_MIDDLE, text, 80,
                    280, 35);
//            content.showTextAligned(Element.ALIGN_MIDDLE, UUID.randomUUID().toString(), 140,
//                    240, 45);
            content.endText();
        }
        stamper.close();
    }

    /**
     * freemarker渲染html
     */
    public static String freeMarkerRender(Map<String, Object> data, String htmlTmp) {
        Writer out = new StringWriter();
        try {
            ConcurrentMap<String, Object> concurrentMap = Maps.newConcurrentMap();
            for (Map.Entry<String, Object> dataMap : data.entrySet()) {
                Object val = dataMap.getValue();
                if(val instanceof String){
                    if (val.toString().contains("<")) {
                        val = val.toString().replace("<", "&lt;");
                    }
                    if (val.toString().contains(">")) {
                        val = val.toString().replace(">", "&gt;");
                    }
                }
                concurrentMap.put(dataMap.getKey(), val);
            }
            // 获取模板,并设置编码方式
            Template template = configuration.getTemplate(htmlTmp);
            template.setEncoding("UTF-8");
            // 合并数据模型与模板
            template.process(concurrentMap, out); //将合并后的数据和模板写入到流中，这里使用的字符流
            out.flush();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    /**
     * iText 中文字体
     */
    private static final class ChinaFontProvide extends XMLWorkerFontProvider {
        @Override
        public Font getFont(final String fontName, final String encoding,
                            final boolean embedded, final float size, final int style,
                            final BaseColor color) {
            BaseFont bf = null;
            try {
                bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                        BaseFont.NOT_EMBEDDED);
            } catch (DocumentException | IOException e) {
//                log.error("创建iText字体失败", e);
            }
            Font font = new Font(bf, size, style, color);
            font.setColor(color);
            return font;
        }
    }
}
